package com.supor.aiot.basket.ui.basket;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.ScaleAnimation;

import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.utils.DialogUtils;
import com.android.baseconfig.common.utils.SystemUtils;
import com.android.baseconfig.common.views.AppBasicDialog;
import com.supor.aiot.basket.R;
import com.supor.aiot.basket.adapter.BasketAdapter;
import com.supor.aiot.basket.adapter.IngredientSelectedListener;
import com.supor.aiot.basket.adapter.IngreidenetListAdapter;
import com.supor.aiot.basket.api.BasketImpl;
import com.supor.aiot.basket.bean.CommonIngredientBean;
import com.supor.aiot.basket.bean.IngredientBean;
import com.supor.aiot.basket.bean.IngredientListBean;
import com.supor.aiot.basket.bean.IsMainIngredients;
import com.supor.aiot.basket.bean.MakeIngredientBean;
import com.supor.aiot.basket.databinding.BasketFragmentBinding;
import com.supor.aiot.basket.view.ButtomDialog;
import com.supor.aiot.basket.view.DoubleClickUtils;
import com.supor.aiot.basket.view.HoriziontalRecycleView;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.base.BaseMVVMFragment;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.rxjava3.functions.Consumer;

public class BasketFragment extends BaseMVVMFragment<BasketViewModel, BasketFragmentBinding> implements View.OnClickListener, IngredientSelectedListener {

    private BasketViewModel mViewModel;
    private boolean recipeManagerState = false;
    private ButtomDialog buttomDialog;
    private BasketAdapter basketAdapter;
    //菜篮子列表
    private List<IngredientBean> basketList = new ArrayList<>();
    //食材清单列表
    private List<IngredientListBean> ingredientList = new ArrayList<>();
    //已选食材列表
    private List<CommonIngredientBean> selectedMainIngredients = new ArrayList<>();
    private List<CommonIngredientBean> selectedOtherIngredients = new ArrayList<>();
    private List<CommonIngredientBean> selectedCommonIngredients = new ArrayList<>();

    private IngreidenetListAdapter ingreidenetListAdapter;
    private List<String> idsList = new ArrayList<>();
    private List<String> basketIDs = new ArrayList<>();
    private List<String> ingredientIDs =new ArrayList<>();

    private int SELECTED_INGREDIENT = 0;
    private int MANAGER_POSITION = 0;
    private static final String BATCH_NO = "BATCH_NO";
    private static final String BATCH_TIME = "BATCH_TIME";
    private static final String TAG = "BasketFragment";
    public static BasketFragment newInstance() {
        return new BasketFragment();
    }
    private AppBasicDialog deleteIngredientDialog;
    private AppBasicDialog deleteBasketDialog;
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(BasketViewModel.class);
        // TODO: Use the ViewModel
//        int statusBarHeight = SystemUtils.getDefaultStatusHeight(activity);
//        bindingView.community.setPadding(bindingView.community.getPaddingLeft(),statusBarHeight,bindingView.community.getPaddingRight(),bindingView.community.getPaddingBottom());
        initRecycleView(false);
        initCommondClick();
    }


    @Override
    public void onResume() {
        super.onResume();
        initOriginState();
    }

    @Override
    protected void initEvent() {
        RxBus3.getInstance().register(Constants.Tag.LOGIN, (Consumer<String>) s -> {
            if (Constants.Value.SUCCESS.equalsIgnoreCase(s)) {
                AppAgent.setLogin(true);
                initOriginState();
            }
        }, this.getClass());

        RxBus3.getInstance().register(Constants.Tag.LOGOUT, (Consumer<String>) s -> {
            if (Constants.Value.SUCCESS.equalsIgnoreCase(s)) {
                AppAgent.setLogin(false);
                initOriginState();
            }
        }, this.getClass());
    }

    private void initCommondClick() {
        bindingView.tvLogin.setOnClickListener(this);
        bindingView.llRecipeOuter.setOnClickListener(this);
        bindingView.llListOuter.setOnClickListener(this);
        bindingView.tvManage.setOnClickListener(this);
        bindingView.llSelectDesc.setOnClickListener(this);
        bindingView.tvMakeList.setOnClickListener(this);
        bindingView.cbForAll.setOnClickListener(this);
        bindingView.rvBasketDetail.setHoriziontalScrollListener(new HoriziontalRecycleView.RecycleScrollListener() {
            @Override
            public void onScrollLeft() {
                if (MANAGER_POSITION==0){
                    checkIngredientList();
                    changeState(true);
                    MANAGER_POSITION=1;
                    changeManageState(MANAGER_POSITION,recipeManagerState);
                }
            }

            @Override
            public void onScrollRight() {
                if (MANAGER_POSITION==1){
                    initBasket();
                    changeState(false);
                    MANAGER_POSITION=0;
                    changeManageState(MANAGER_POSITION,recipeManagerState);
                }
            }
        });
    }

    private void initRecycleView(boolean state) {
        basketAdapter=new BasketAdapter(basketList,getActivity());
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        bindingView.rvBasketDetail.setLayoutManager(layoutManager);
        basketAdapter.setIngredientSelectedListener(this);
        basketAdapter.setBasketListener(new BasketAdapter.OnBasketItemListener() {
            @Override
            public void onCheckBox(int position, boolean state1) {
                if (state1){
                    if (!basketIDs.contains(basketList.get(position).getAutoId()+"")){
                        basketIDs.add(basketList.get(position).getAutoId()+"");
                    }

                    if (basketIDs.size()==basketList.size()){
                        bindingView.cbForAll.setChecked(true);
                    }
                }else {
                    if (basketIDs.contains(basketList.get(position).getAutoId()+"")){
                        basketIDs.remove(basketList.get(position).getAutoId()+"");

                    }
                    bindingView.cbForAll.setChecked(false);
                }
                if (recipeManagerState){
                    checkDeleteRecipe();
                }else {
                    checkClickedRecipe();
                    changeBasketState(basketList.get(position).getAutoId()+"",state1?1:0);

                }
            }

            @Override
            public void onCheckDetail(int position) {
                AppAgent.startRecipePage(basketList.get(position).getRecipeId(), basketList.get(position).getModelId());
            }
        });

        bindingView.rvBasketDetail.setFocusableInTouchMode(false);
        bindingView.rvBasketDetail.requestFocus();

        ingreidenetListAdapter = new IngreidenetListAdapter(ingredientList,getActivity());
        ingreidenetListAdapter.setOnItemClickListener((position, state12) -> {
            if (state12){
                if (!ingredientIDs.contains(ingredientList.get(position).getAutoId()+""))ingredientIDs.add(ingredientList.get(position).getAutoId()+"");
                if (ingredientIDs.size()==ingredientList.size()){
                    bindingView.cbForAll.setChecked(true);
                }
            }else {
                ingredientIDs.remove(ingredientList.get(position).getAutoId()+"");
                bindingView.cbForAll.setChecked(false);
            }
            if (ingredientIDs.size()>0){
                bindingView.tvMakeList.setEnabled(true);
                bindingView.tvMakeList.setBackground(getActivity().getDrawable(R.drawable.red_colour_bg));
            }else {
                bindingView.tvMakeList.setEnabled(false);
                bindingView.tvMakeList.setBackground(getActivity().getDrawable(R.drawable.gray_colour_bg));
            }
        });
        if (state){
            bindingView.rvBasketDetail.setAdapter(ingreidenetListAdapter);
            ingredientIDs.clear();
        }else {
            bindingView.rvBasketDetail.setAdapter(basketAdapter);
            basketIDs.clear();
        }
    }


    @SuppressLint("AutoDispose")
    private void changeBasketState(String id,int state){
        BasketImpl.getInstance().selectAllIngredient(id,state).subscribe(result -> {
            if (result.isSuccess()) {
                initBasket();
            } else {
                Log.e(TAG, "state error");
            }
        }, throwable -> {
            Log.e(TAG, "state查询失败: " + throwable.getMessage());

        });
    }

    /**
     * 初始化初始Dialog状态,CheckBox状态
     */
    private void initSelectedIngredients(){
        idsList.clear();
        basketIDs.clear();
        if (basketList.size()>0){
            for (IngredientBean bean:basketList) {
                if (bean.getIsMainIngredients().size() > 0) {
                    boolean checked = true;
                    for (IsMainIngredients ingredients : bean.getIsMainIngredients()) {
                        if (ingredients.getIsSelect() == 0) checked = false;
                    }
                    if (bean.getIsTsIngredients().size() > 0) {
                        for (IsMainIngredients ingredients : bean.getIsTsIngredients()) {
                            if (ingredients.getIsSelect() == 0) checked = false;
                        }
                    }
                    if (checked){
                        if (!basketIDs.contains(bean.getAutoId()+"")){
                            basketIDs.add(bean.getAutoId()+"");
                        }
                    }
                }
            }
            if (basketIDs.size()==basketList.size()){
                bindingView.cbForAll.setChecked(true);
            }else {
                bindingView.cbForAll.setChecked(false);
            }

            for (IngredientBean bean:basketList){
                idsList.add(bean.getAutoId()+"");
            }
        }

        if (idsList.size()>0){
            String ids = "";
            for (int i=0;i<idsList.size();i++){
                if (i>0){
                    ids=ids+","+idsList.get(i);
                }else {
                    ids+=idsList.get(i);
                }
            }
            getIngredients(ids);
        }

    }

    @SuppressLint("AutoDispose")
    private void initBasket(){
        BasketImpl.getInstance().requestBasket(0,100).subscribe(result -> {
            if (result.isSuccess()) {
                if (result.data.rows!=null){
                    basketList.clear();
                    basketList.addAll(result.data.rows);
                    basketAdapter.notifyDataSetChanged();
                    if (basketList.size()>0){
                        initSelectedIngredients();
                        bindingView.llNotLogin.setVisibility(View.GONE);
                        bindingView.rlSelectAll.setVisibility(View.VISIBLE);
                        if (MANAGER_POSITION==0)bindingView.tvManage.setVisibility(View.VISIBLE);
                    }else {
                        bindingView.llNotLogin.setVisibility(View.VISIBLE);
                        bindingView.rlSelectAll.setVisibility(View.GONE);
                        bindingView.ivNoneBg.setImageResource(R.mipmap.basket_recipe_none);
                        bindingView.tvLogin.setVisibility(View.GONE);
                        bindingView.tvSuguest.setVisibility(View.VISIBLE);
                        bindingView.tvCommonBg.setText(getActivity().getResources().getString(R.string.none_basket_recipe));
                        bindingView.tvSuguest.setText(getActivity().getResources().getString(R.string.basket_recipe_tips));
                        if (MANAGER_POSITION==0)bindingView.tvManage.setVisibility(View.GONE);
                    }
                }
                closeLoading();
            } else {
                Log.e(TAG, "recipe error");
                showError();
                closeLoading();
            }
        }, throwable -> {
            Log.e(TAG, "recipe查询失败: " + throwable.getMessage());
            showError();
            closeLoading();
        });
    }

    @Override
    protected void onRefresh() {
        super.onRefresh();
        initOriginState();
    }

    @SuppressLint("AutoDispose")
    private void checkIngredientList(){
        BasketImpl.getInstance().checkIngredientList().subscribe(result -> {
            if (result.isSuccess()) {
                if (result.data.rows!=null){
                    ingredientList.clear();
                    ingredientList.addAll(result.data.rows);
                    ingreidenetListAdapter.notifyDataSetChanged();
                    if (ingredientList.size()>0){
                        bindingView.llNotLogin.setVisibility(View.GONE);
                        if (MANAGER_POSITION==1)bindingView.tvManage.setVisibility(View.VISIBLE);
                    }else {
                        bindingView.llNotLogin.setVisibility(View.VISIBLE);
                        bindingView.ivNoneBg.setImageResource(R.mipmap.basket_ingredienlist_none);
                        bindingView.tvLogin.setVisibility(View.GONE);
                        bindingView.tvSuguest.setVisibility(View.VISIBLE);
                        bindingView.tvCommonBg.setText(getActivity().getResources().getString(R.string.none_basket_list));
                        bindingView.tvSuguest.setText(getActivity().getResources().getString(R.string.see_basket_list));
                        if (MANAGER_POSITION==1)bindingView.tvManage.setVisibility(View.GONE);
                    }
                }
                closeLoading();
            } else {
                Log.e(TAG, "recipe error");
                closeLoading();
            }
        }, throwable -> {
            Log.e(TAG, "recipe查询失败: " + throwable.getMessage());
            closeLoading();
        });
    }

    @SuppressLint("AutoDispose")
    private void makeIngredientList(String ids){
        BasketImpl.getInstance().makeIngredientList(ids).subscribe(result -> {
            if (result.isSuccess()) {
                MakeIngredientBean bean = result.data;
                Intent intent = new Intent(getActivity(),IngredientListActivity.class);
                intent.putExtra(BATCH_NO,bean.getListBatchNo());
                intent.putExtra(BATCH_TIME,bean.getTime());
                getActivity().startActivity(intent);
            } else {
                Log.e(TAG, "recipe error");
            }
        }, throwable -> {
            Log.e(TAG, "recipe查询失败: " + throwable.getMessage());
            // ToastUtils.getInstance().showCustomToast(throwable.getMessage());
        });
    }


    @SuppressLint("AutoDispose")
    private void deleteIngredientList(String ids){
        BasketImpl.getInstance().deleteIngredientList(ids).subscribe(result -> {
            if (result.isSuccess()) {
                ingredientIDs.clear();
                bindingView.cbForAll.setChecked(false);
                recipeManagerState=false;
                changeManageState(MANAGER_POSITION,recipeManagerState);
                checkIngredientList();
            } else {
                Log.e(TAG, "recipe error");
            }
        }, throwable -> {
            Log.e(TAG, "recipe查询失败: " + throwable.getMessage());
            // ToastUtils.getInstance().showCustomToast(throwable.getMessage());
        });
    }


    @SuppressLint("AutoDispose")
    private void deleteBasketList(String ids){
        BasketImpl.getInstance().deleteBasket(ids).subscribe(result -> {
            if (result.isSuccess()) {
                basketIDs.clear();
                bindingView.cbForAll.setChecked(false);
                recipeManagerState=false;
                changeManageState(MANAGER_POSITION,recipeManagerState);
                initBasket();
            } else {
                Log.e(TAG, "recipe error");
            }
        }, throwable -> {
            Log.e(TAG, "recipe查询失败: " + throwable.getMessage());
            // ToastUtils.getInstance().showCustomToast(throwable.getMessage());
        });
    }

    @SuppressLint("AutoDispose")
    private void getIngredients(String ids){
        BasketImpl.getInstance().getIngredients(ids).subscribe(result -> {
            selectedMainIngredients.clear();
            selectedOtherIngredients.clear();
            selectedCommonIngredients.clear();
            selectedMainIngredients.addAll(result.data.getIsMainIngredients());
            selectedCommonIngredients.addAll(result.data.getIsCgIngredients());
            selectedOtherIngredients.addAll(result.data.getIsTsIngredients());

            SELECTED_INGREDIENT=selectedMainIngredients.size()+selectedOtherIngredients.size()+selectedCommonIngredients.size();
            Log.e(TAG,"selected size ="+SELECTED_INGREDIENT);
            if (!recipeManagerState){
                if (SELECTED_INGREDIENT>0){
                    bindingView.rlSelectDesc.setVisibility(View.VISIBLE);
                    bindingView.tvSelectedFoods.setText(AppAgent.getApp().getString(R.string.has_selected) + SELECTED_INGREDIENT + AppAgent.getApp().getString(R.string.selected_foods));
                    bindingView.tvMakeList.setEnabled(true);
                    bindingView.tvMakeList.setBackground(AppAgent.getApp().getDrawable(R.drawable.main_colour_bg));
                }else {
                    bindingView.rlSelectDesc.setVisibility(View.GONE);
                    bindingView.tvMakeList.setEnabled(false);
                    bindingView.tvMakeList.setBackground(AppAgent.getApp().getDrawable(R.drawable.gray_colour_bg));
                }
            }
        }, throwable -> {
            Log.e(TAG, "recipe查询失败: " + throwable.getMessage());
            // ToastUtils.getInstance().showCustomToast(throwable.getMessage());
        });
    }

    /**
     * 管理初始状态
     */
    private void checkDeleteRecipe(){
        if (MANAGER_POSITION==0){
            if (basketIDs.size()==0){
                bindingView.rlSelectDesc.setVisibility(View.GONE);
                bindingView.tvMakeList.setEnabled(false);
                bindingView.tvMakeList.setBackground(getActivity().getDrawable(R.drawable.gray_colour_bg));
            }else {
                bindingView.rlSelectDesc.setVisibility(View.VISIBLE);
                bindingView.tvMakeList.setEnabled(true);
                bindingView.tvMakeList.setBackground(getActivity().getDrawable(R.drawable.red_colour_bg));
                bindingView.tvSelectedFoods.setText(getActivity().getString(R.string.has_selected)+basketIDs.size()+getActivity().getString(R.string.selected_recipes));
            }
        }else if (MANAGER_POSITION == 1){
            if (ingredientIDs.size()==0){
                bindingView.rlSelectDesc.setVisibility(View.GONE);
                bindingView.tvMakeList.setEnabled(false);
                bindingView.tvMakeList.setBackground(getActivity().getDrawable(R.drawable.gray_colour_bg));
            }else {
                bindingView.rlSelectDesc.setVisibility(View.VISIBLE);
                bindingView.tvMakeList.setEnabled(true);
                bindingView.tvMakeList.setBackground(getActivity().getDrawable(R.drawable.red_colour_bg));
            }
        }

    }

    /**
     * 默认初始状态
     */
    private void checkClickedRecipe(){

        if (MANAGER_POSITION==0){
            if (basketIDs.size()==0){
                bindingView.rlSelectDesc.setVisibility(View.GONE);
                bindingView.tvMakeList.setEnabled(false);
                bindingView.tvMakeList.setBackground(getActivity().getDrawable(R.drawable.gray_colour_bg));
            }else {
                bindingView.rlSelectDesc.setVisibility(View.VISIBLE);
                bindingView.tvMakeList.setEnabled(true);
                bindingView.tvMakeList.setBackground(getActivity().getDrawable(R.drawable.main_colour_bg));

            }
        }else if (MANAGER_POSITION == 1){
            if (ingredientIDs.size()==0){
                bindingView.rlSelectDesc.setVisibility(View.GONE);
                bindingView.tvMakeList.setEnabled(false);
                bindingView.tvMakeList.setBackground(getActivity().getDrawable(R.drawable.gray_colour_bg));
            }else {
                bindingView.rlSelectDesc.setVisibility(View.VISIBLE);
                bindingView.tvMakeList.setEnabled(true);
                bindingView.tvMakeList.setBackground(getActivity().getDrawable(R.drawable.main_colour_bg));
            }
        }

    }

    private void initOriginState() {
        if (!AppAgent.isLogin()) {
            bindingView.llNotLogin.setVisibility(View.VISIBLE);
            bindingView.rlBasket.setVisibility(View.GONE);
        }else {
            bindingView.llNotLogin.setVisibility(View.GONE);
            bindingView.rlBasket.setVisibility(View.VISIBLE);
            showLoading();
            if (MANAGER_POSITION==0){
                initBasket();
            }else {
                checkIngredientList();
            }
        }
    }


    private void changeState(boolean state){
        if (state){
            bindingView.tvBasketRecipe.setTextColor(getActivity().getResources().getColor(R.color.content_assist));
            bindingView.tvBasketRecipe.setTextSize(TypedValue.COMPLEX_UNIT_PX,getActivity().getResources().getDimension(R.dimen.sp_14));
            bindingView.tvBasketList.setTextColor(getActivity().getResources().getColor(R.color.black));
            bindingView.tvBasketList.setTextSize(TypedValue.COMPLEX_UNIT_PX,getActivity().getResources().getDimension(R.dimen.sp_20));
            bindingView.tvBasketRecipe.setDotVisible(false);
            bindingView.tvBasketList.setDotVisible(true);
//            showScaleAnimation(bindingView.basketListBg);
//            hideScaleAnimation(bindingView.basketRecipeBg);
            initRecycleView(state);
            bindingView.rlSelectAll.setVisibility(View.GONE);
        }else {
            bindingView.tvBasketList.setTextColor(getActivity().getResources().getColor(R.color.content_assist));
            bindingView.tvBasketList.setTextSize(TypedValue.COMPLEX_UNIT_PX,getActivity().getResources().getDimension(R.dimen.sp_14));
            bindingView.tvBasketRecipe.setTextColor(getActivity().getResources().getColor(R.color.black));
            bindingView.tvBasketRecipe.setTextSize(TypedValue.COMPLEX_UNIT_PX,getActivity().getResources().getDimension(R.dimen.sp_20));
            bindingView.tvBasketRecipe.setDotVisible(true);
            bindingView.tvBasketList.setDotVisible(false);
//            showScaleAnimation(bindingView.basketRecipeBg);
//            hideScaleAnimation(bindingView.basketListBg);
            initRecycleView(state);
            if (basketList.size()>0)bindingView.rlSelectAll.setVisibility(View.VISIBLE);
        }
        recipeManagerState=false;
    }

    private void changeManageState(int position,boolean managerState){
        if (managerState){
            bindingView.tvManage.setText(getActivity().getString(R.string.basket_complete));
            if (position==0){
                bindingView.tvMakeList.setText(getActivity().getString(R.string.delete_recipe));
                bindingView.tvSelectedFoods.setVisibility(View.VISIBLE);
                bindingView.llSelectDesc.setVisibility(View.GONE);
            }else if (position==1){
                bindingView.tvMakeList.setText(getActivity().getString(R.string.delete_list));
                bindingView.tvSelectedFoods.setVisibility(View.GONE);
                bindingView.llSelectDesc.setVisibility(View.GONE);
                ingreidenetListAdapter.changeCBstate(true);
                ingreidenetListAdapter.notifyDataSetChanged();
                bindingView.cbForAll.setChecked(false);
            }
            checkDeleteRecipe();
        }else {
            bindingView.tvManage.setText(getActivity().getString(R.string.basket_manage));
            if (position==1){
                bindingView.rlSelectAll.setVisibility(View.GONE);
                ingreidenetListAdapter.changeCBstate(false);
                ingreidenetListAdapter.notifyDataSetChanged();
            }else if (position == 0){
                bindingView.tvSelectedFoods.setVisibility(View.VISIBLE);
                bindingView.llSelectDesc.setVisibility(View.VISIBLE);
                bindingView.rlSelectAll.setVisibility(View.VISIBLE);
                bindingView.tvMakeList.setText(getActivity().getString(R.string.make_list));
                /*basketAdapter.setCBallState(false,false);
                initSelectedIngredients();*/
                initBasket();
            }
            checkClickedRecipe();
        }
    }

    public void showScaleAnimation(View view) {

        /**
         * ScaleAnimation第三种构造在第二种构造的基础上，可以通过多种方式指定轴心的位置，通过Type来约束
         *
         * @param fromX 同上
         * @param toX 同上
         * @param fromY 同上T
         * @param toY 同上
         * @param pivotXType 用来约束pivotXValue的取值。取值有三种：Animation.ABSOLUTE，Animation.RELATIVE_TO_SELF，Animation.RELATIVE_TO_PARENT
         * Type：Animation.ABSOLUTE：绝对，如果设置这种类型，后面pivotXValue取值就必须是像素点；比如：控件X方向上的中心点，pivotXValue的取值mIvScale.getWidth() / 2f
         *            Animation.RELATIVE_TO_SELF：相对于控件自己，设置这种类型，后面pivotXValue取值就会去拿这个取值是乘上控件本身的宽度；比如：控件X方向上的中心点，pivotXValue的取值0.5f
         *            Animation.RELATIVE_TO_PARENT：相对于它父容器（这个父容器是指包括这个这个做动画控件的外一层控件）， 原理同上，
         * @param pivotXValue  配合pivotXType使用，原理在上面
         * @param pivotYType 原理同上
         * @param pivotYValue 原理同上
         */
        ScaleAnimation scaleAnimation2 = new ScaleAnimation(0f, 1f, 0f, 1f, ScaleAnimation.ABSOLUTE, view.getWidth() / 2f, ScaleAnimation.ABSOLUTE, view.getHeight() / 2f);
        //设置动画持续时长
        scaleAnimation2.setDuration(500);
        //设置动画结束之后的状态是否是动画的最终状态，true，表示是保持动画结束时的最终状态
        scaleAnimation2.setFillAfter(true);
        //设置动画结束之后的状态是否是动画开始时的状态，true，表示是保持动画开始时的状态
        //scaleAnimation2.setFillBefore(true);
        //设置动画的重复模式：反转REVERSE和重新开始RESTART
        //scaleAnimation2.setRepeatMode(ScaleAnimation.REVERSE);
        //设置动画播放次数
        //scaleAnimation2.setRepeatCount(ScaleAnimation.INFINITE);
        //开始动画
        view.startAnimation(scaleAnimation2);
    }

    public void hideScaleAnimation(View view) {

        /**
         * ScaleAnimation第三种构造在第二种构造的基础上，可以通过多种方式指定轴心的位置，通过Type来约束
         *
         * @param fromX 同上
         * @param toX 同上
         * @param fromY 同上T
         * @param toY 同上
         * @param pivotXType 用来约束pivotXValue的取值。取值有三种：Animation.ABSOLUTE，Animation.RELATIVE_TO_SELF，Animation.RELATIVE_TO_PARENT
         * Type：Animation.ABSOLUTE：绝对，如果设置这种类型，后面pivotXValue取值就必须是像素点；比如：控件X方向上的中心点，pivotXValue的取值mIvScale.getWidth() / 2f
         *            Animation.RELATIVE_TO_SELF：相对于控件自己，设置这种类型，后面pivotXValue取值就会去拿这个取值是乘上控件本身的宽度；比如：控件X方向上的中心点，pivotXValue的取值0.5f
         *            Animation.RELATIVE_TO_PARENT：相对于它父容器（这个父容器是指包括这个这个做动画控件的外一层控件）， 原理同上，
         * @param pivotXValue  配合pivotXType使用，原理在上面
         * @param pivotYType 原理同上
         * @param pivotYValue 原理同上
         */
        ScaleAnimation scaleAnimation2 = new ScaleAnimation(1f, 0f, 1f, 0f, ScaleAnimation.RELATIVE_TO_SELF, 0.5f, ScaleAnimation.RELATIVE_TO_SELF, 0.5f);
        //设置动画持续时长
        scaleAnimation2.setDuration(400);
        //设置动画结束之后的状态是否是动画的最终状态，true，表示是保持动画结束时的最终状态
        scaleAnimation2.setFillAfter(true);
        //开始动画
        view.startAnimation(scaleAnimation2);
    }

    @Override
    public int setContent() {
        return R.layout.basket_fragment;
    }

    @Override
    public void onClick(View view) {
        if (view.getId()==R.id.tv_login){
            SuporPresenter.getInstance().getCmccHelper().displayLogin(true);
        }else if (view.getId()==R.id.ll_recipe_outer){
            showLoading();
            initBasket();
            changeState(false);
            MANAGER_POSITION=0;
            changeManageState(MANAGER_POSITION,recipeManagerState);
        }else if (view.getId()==R.id.ll_list_outer){
            showLoading();
            checkIngredientList();
            changeState(true);
            MANAGER_POSITION=1;
            changeManageState(MANAGER_POSITION,recipeManagerState);
        }else if (view.getId()==R.id.tv_manage){
            recipeManagerState = !recipeManagerState;
            if ((MANAGER_POSITION==0&&basketList.size()>0)||(MANAGER_POSITION==1&&ingredientList.size()>0)){
                bindingView.rlSelectAll.setVisibility(View.VISIBLE);
                changeManageState(MANAGER_POSITION,recipeManagerState);
            }
        }else if (view.getId()==R.id.cb_for_all){
            boolean state = bindingView.cbForAll.isChecked();
            if (recipeManagerState){
                if (MANAGER_POSITION==0){
                    if (state){
                        basketIDs.clear();
                        for (int i=0;i<basketList.size();i++){
                            basketIDs.add(basketList.get(i).getAutoId()+"");
                        }
                    }else {
                        basketIDs.clear();
                    }
                    checkDeleteRecipe();
                    basketAdapter.setCBallState(recipeManagerState,state);
                }else {
                    ingreidenetListAdapter.setIsAllSelected(state);
                }
            }else {
                if (MANAGER_POSITION==0){
                    basketAdapter.setCBallState(recipeManagerState);
                    if (idsList.size()>0){
                        String ids = "";
                        for (int i=0;i<idsList.size();i++){
                            if (i>0){
                                ids=ids+","+idsList.get(i);
                            }else {
                                ids+=idsList.get(i);
                            }
                        }
                        changeBasketState(ids,state?1:0);
                    }
                }
            }
        }else if (view.getId()==R.id.ll_select_desc){
            ButtomDialog.Builder builder =  new ButtomDialog.Builder(getActivity());
            builder.setMainIngredient(selectedMainIngredients);
            builder.setOtherIngredient(selectedOtherIngredients);
            builder.setCommonIngredient(selectedCommonIngredients);
            builder.setConfirmListener(view1 -> {
                if (DoubleClickUtils.isFastDoubleClick())return;
                makeIngredients();
                buttomDialog.cancel();
            });
            builder.setShadow(true);
            builder.setCanCancel(true);
            buttomDialog = builder.create();
            buttomDialog.show();
        }else if (view.getId()==R.id.tv_make_list){
            if (DoubleClickUtils.isFastDoubleClick())return;
            if (recipeManagerState){
                if (MANAGER_POSITION==0){
                    deleteBasketDialog = DialogUtils.opDialog(getActivity(), R.string.delete_recipe_tips, R.string.notice, R.string.common_delete, R.string.not_delete, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (basketIDs.size()>0){
                                String basketID = "";
                                for (int j=0;j<basketIDs.size();j++){
                                    if (j>0){
                                        basketID+=","+basketIDs.get(j);
                                    }else {
                                        basketID+=basketIDs.get(j);
                                    }
                                }
                                deleteBasketList(basketID);
                            }
                            deleteBasketDialog.cancel();
                        }
                    });
                    deleteBasketDialog.show();
                }else {
                    deleteIngredientDialog = DialogUtils.opDialog(getActivity(), R.string.delete_list_tips, R.string.notice, R.string.common_delete, R.string.not_delete, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                            if (ingredientIDs.size()>0){
                                String ingredientID = "";
                                for (int j=0;j<ingredientIDs.size();j++){
                                    if (j>0){
                                        ingredientID+=","+ingredientIDs.get(j);
                                    }else {
                                        ingredientID+=ingredientIDs.get(j);
                                    }
                                }
                                deleteIngredientList(ingredientID);
                            }
                            deleteIngredientDialog.cancel();
                        }
                    });
                    deleteIngredientDialog.show();
                }
            }else {
                makeIngredients();
            }
        }
    }

    /**
     * 生成清单
     */
    private void makeIngredients(){
        String ids = "";
        for (int i=0;i<idsList.size();i++){
            if (i>0){
                ids=ids+","+idsList.get(i);
            }else {
                ids+=idsList.get(i);
            }
        }
        makeIngredientList(ids);
    }

    // @Override
    // public void updateNetStatus(int type) {
    // }

    @Override
    public void OnIngredientSelected() {
        initBasket();
    }
}

